package com.yljk.yljkproject.ui.webview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.widget.NestedScrollView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.yilijk.base.constants.UserInfo;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yljk.homedoctor.model.entity.AgreeBean;
import com.yljk.homedoctor.view.view.PersonalTaxDialog;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.oldbase.ModuleBaseActivity;
import com.yljk.servicemanager.view.CustomeDialog;
import com.yljk.yljkproject.R;
import com.yljk.yljkproject.entity.CustomeEntity;
import com.yljk.yljkproject.entity.PersonalTaxBean;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;

import crossoverone.statuslib.StatusUtil;
/**
 * Create By shicheng
 *
 * 原生web页加载
 * Android web page (WebView) load
 *
 */
@Route(path = RouterApi.WebActivity)
public class WebViewActivity extends ModuleBaseActivity{

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private ImageView webBack;
    private TextView webviewtitle;
    private WebView downloadBoring;
    private CustomeDialog customeDialog;

    private NestedScrollView webviewPersonalTax;
    private TextView webviewPersonalTaxMessage;
    private TextView webviewPersonalTaxDisagree;
    private TextView webviewPersonalTaxAgree;

    @Autowired
    String title;
    @Autowired
    String url;
    @Autowired
    boolean ishtml;
    @Autowired
    boolean isShowLoading;
    @Autowired
    boolean isPersonalTax;
    @Autowired
    boolean isCustomor;


    private Handler handler = new Handler();

    @Override
    public int bondLayout() {
        return R.layout.activity_web_view;
    }

    @Override
    public void initView() {
        customeDialog = new CustomeDialog.Builder(this).create();
        if (isShowLoading){
            customeDialog.show();
        }
        ARouter.getInstance().inject(this);   //注入
        //状态栏修改
        StatusUtil.setUseStatusBarColor(this, Color.WHITE);
        StatusUtil.setSystemStatus(this,false,true);
        webBack = findViewById(R.id.web_back);
        webviewtitle = findViewById(R.id.webviewtitle);
        downloadBoring = findViewById(R.id.download_boring);

        webviewPersonalTax = (NestedScrollView) findViewById(R.id.webview_personalTax);
        webviewPersonalTaxMessage = (TextView) findViewById(R.id.webview_personalTax_message);
        webviewPersonalTaxDisagree = (TextView) findViewById(R.id.webview_personalTax_disagree);
        webviewPersonalTaxAgree = (TextView) findViewById(R.id.webview_personalTax_agree);
        if (isPersonalTax){
            initPersonalTax();
            webviewPersonalTax.setVisibility(View.VISIBLE);
            downloadBoring.setVisibility(View.GONE);
        }else{
            webviewPersonalTax.setVisibility(View.GONE);
            downloadBoring.setVisibility(View.VISIBLE);
        }
        webSetting();
    }


    @Override
    public void initData() {
        webviewtitle.setText(title);
        if (ishtml){
            downloadBoring.loadDataWithBaseURL(null,url,"text/html","UTF-8",null);
        }else if (isPersonalTax){
            RequestParams params = new RequestParams();
            params.put("documentNo","jingyingfuwuhezuoxieyi");
            HttpUtils.get(UrlApi.getByDocumentNo, params, new HttpCallBack<PersonalTaxBean>() {
                @Override
                public void onSuccess(PersonalTaxBean result, int code) {
                    if (result.isResult()){
                        PersonalTaxBean.DataBean data = result.getData();
                        webviewtitle.setText(data.getTitle());
                        RichText.from(data.getContent()).bind(this)
                                .showBorder(false)
                                .size(ImageHolder.MATCH_PARENT, ImageHolder.WRAP_CONTENT)
                                .into(webviewPersonalTaxMessage);


                    }
                }

                @Override
                public void onFailure(String failureMsg, int statusCode) {

                }
            });
        }else if (isCustomor) {
            HttpUtils.get(UrlApi.customer, new HttpCallBack<CustomeEntity>() {
                @Override
                public void onSuccess(CustomeEntity result, int code) {
                    String s = result.getData().getUrl().replaceAll("null", "医生端");
                    if ("200".equals(result.getStatus())) {
                        downloadBoring.loadUrl(s);
                    }
                }

                @Override
                public void onFailure(String failureMsg, int statusCode) {

                }
            });
        } else{
            //对应字符替换 适配URL
            if (url.contains("${passportId}")){
                url = url.replace("${passportId}", SharedPreferencesUtils.getInstance().getString(UserInfo.passportId,""));
            }

            if (url.contains("${timestamp}")){
                url = url.replace("${timestamp}", System.currentTimeMillis()+"");
            }

            if (url.contains("${token}")){
                url = url.replace("${token}", SharedPreferencesUtils.getInstance().getString(UserInfo.token,""));
            }

            downloadBoring.loadUrl(url);
        }

        if (customeDialog.isShowing()){
            customeDialog.cancel();
        }
    }

    private void webSetting() {
        downloadBoring.addJavascriptInterface(new WebJavascriptInterface(this),"WebJavascriptInterface");
        downloadBoring.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        /* 设置支持Js,必须设置的,基本大多数网页都涉及js */
        downloadBoring.getSettings().setJavaScriptEnabled(true);
        /* 设置为使用webview推荐的窗口，主要是为了配合下一个属性 */
        downloadBoring.getSettings().setUseWideViewPort(false);
        /* 设置网页自适应屏幕大小，该属性必须和上一属性配合使用 */
        downloadBoring.getSettings().setLoadWithOverviewMode(true);

        downloadBoring.setWebViewClient(new ArticleWebViewClient(this));
        //        配置webview保存密码选项
        downloadBoring.getSettings().setSavePassword(false);

        downloadBoring.getSettings().setAllowFileAccess(true);
        downloadBoring.getSettings().setDomStorageEnabled(true);
        downloadBoring.getSettings().setBlockNetworkImage(false);
        downloadBoring.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        downloadBoring.getSettings().setLoadsImagesAutomatically(true);
        downloadBoring.getSettings().setSupportMultipleWindows(false);
        String userAgentString = downloadBoring.getSettings().getUserAgentString();
        String IVversion = " IV."+ DevicesUtils.getVersionName();
        userAgentString =  userAgentString + " MicroMessenger/4.5.255"+" "+ BaseConfig.Web.WebView_UserAgent;
        downloadBoring.getSettings().setUserAgentString(userAgentString+IVversion);
        downloadBoring.setWebChromeClient(new SelfWebChromeClient(uploadMessage,uploadMessageAboveL,this) {//此行代码可以保证JavaScript的Alert弹窗正常弹出
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title) && !ishtml){
                    webviewtitle.setText(title);
                }
            }
        });
        downloadBoring.getSettings().setMediaPlaybackRequiresUserGesture(false);
        downloadBoring.getSettings().setBuiltInZoomControls(true);
        downloadBoring.getSettings().setDisplayZoomControls(false);
    }

    @Override
    public void initEvent() {
        webBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPersonalTax){
                    HttpUtils.get(UrlApi.UpdateState, personalTaxJSONObject(3), new HttpCallBack<Object>() {
                        @Override
                        public void onSuccess(Object result, int code) {
                            if (code == 200){
                                finish();
                            }
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {

                        }
                    });
                }else{
                    if (downloadBoring.canGoBack()){
                        downloadBoring.goBack();
                    }else{
                        finish();
                    }
                }
            }
        });

        if (isPersonalTax){
            ClickUtils.setFastOnClickListener(webviewPersonalTaxDisagree, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HttpUtils.get(UrlApi.UpdateState, personalTaxJSONObject(2), new HttpCallBack<AgreeBean>() {
                        @Override
                        public void onSuccess(AgreeBean result, int code) {
                            if (result.isResult()) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        personalTaxDialogBuilder.setTitle("提示");
                                        personalTaxDialogBuilder.setMessage1("如需再次了解，请联系客服");
                                        personalTaxDialog = personalTaxDialogBuilder.create();
                                        personalTaxDialog.setCancelable(false);
                                        if (!personalTaxDialog.isShowing()) {
                                            personalTaxDialog.show();
                                        }
                                    }
                                });
                            }else{
                                Toast.makeText(WebViewActivity.this, result.getMsg()+"", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {

                        }
                    });
                }
            });
            ClickUtils.setFastOnClickListener(webviewPersonalTaxAgree, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HttpUtils.get(UrlApi.UpdateState, personalTaxJSONObject(1), new HttpCallBack<AgreeBean>() {
                        @Override
                        public void onSuccess(AgreeBean agreeBean, int code) {
                            if (agreeBean.isResult()){
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        personalTaxDialogBuilder.setTitle("提示");
                                        personalTaxDialogBuilder.setMessage1("您已成功签约，合同次日生效");
                                        personalTaxDialog = personalTaxDialogBuilder.create();
                                        personalTaxDialog.setCancelable(false);
                                        if (!personalTaxDialog.isShowing()){
                                            personalTaxDialog.show();
                                        }
                                    }
                                });
                            }else{
                                Toast.makeText(WebViewActivity.this, agreeBean.getMsg()+"", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {

                        }
                    });
                }
            });
        }


    }
    /**
     * 个税通知弹窗
     */
    private PersonalTaxDialog.Builder personalTaxDialogBuilder;
    private PersonalTaxDialog personalTaxDialog;
    private void initPersonalTax() {
        personalTaxDialogBuilder = new PersonalTaxDialog.Builder(this);
        personalTaxDialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                personalTaxDialog.dismiss();
                finish();
            }
        });
    }

    /**
     * 个税协议入参
     */
    RequestParams personalTaxJSONObject(int state){
        RequestParams params = new RequestParams();
        params.put("state",state);
        return params;
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        customeDialog = null;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }






}


